// 普通函数获取异步返回值
// 第二个参数，禁用promise
export function toPromise(fn, flag = true) {
    let time = 0
    return new Promise((resolve) => {
        const interval = setInterval(() => {
            time++
            let res = fn()
            if (!flag) {
                resolve(res)
            } else if ((Array.isArray(res) && res.length) || (!Array.isArray(res) && (res || res === 0))) {
                // 是数组且数组有数据 或 不是数组且不为空
                clearInterval(interval)
                resolve(res)
            } else if (time > 100) {
                clearInterval(interval)
                resolve(res)
            }
        }, 50)
    })
}

export function isEquals(obj1, obj2) {
    return JSON.stringify(obj1) === JSON.stringify(obj2)
}

export function isUndefined(val) {
    return typeof val === 'undefined'
}

//导出默认配置
export const baseConfig = {
    timeout: 120000,
    dict: {
        url: '/sys/dict/list',
        label: 'dicKey',
        value: 'dicValue',
        type: 'type'
    },
    router: {
        url: '/getRouters',
        starter: null, //stater必传，vueRouter 实例
        baseRouter: 'Main',
        dynamic: false, //默认使用qc-admin生成动态路由,此时需要配置srcPath
        srcPath: '', //动态路由时，需要寻找被依赖项目的组件所在目录
        import: () => { }
    }
}

export function setConfig(config) {
    Object.assign(baseConfig, config)
}

//设置动态路由
export function setRoutes(router, routes, parent = 'Main') {
    routes.forEach(route => {
        router.addRoute(parent, route)
    })
    router.addRoute({
        path: '/*',
        redirect: '/404',
    })
}


export const setForm = (form1, form2, exclude = []) => {
    Object.keys(form1).map(key => {
        if (!exclude.includes(key)) {
            if (Object.prototype.hasOwnProperty.call(form2, key)) {
                form1[key] = form2[key]
            }
        }
    })
}

export const resetForm = (form) => {
    Object.keys(form).map(key => {
        if (Array.isArray(form[key])) {
            form[key] = []
        } else {
            form[key] = ''
        }
    })
}

export const cropForm = (form, crops = []) => {
    let newForm = {}
    Object.keys(form).map(key => {
        if (!crops.includes(key)) {
            newForm[key] = form[key]
        }
    })
    return newForm
}

export const debounce = (fn, wait) => {
    let timer;
    let immediate = true
    let isFn = false;
    return function () {
        clearTimeout(timer);
        isFn = immediate
        timer = setTimeout(() => {
            !isFn && fn()
            immediate = true
        }, wait);
        if (immediate) {
            fn()
            immediate = false
        }
    }
}

